/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libgp2x.

    libgp2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libgp2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libgp2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdarg.h>

#include "gp2x_internal.h"

int __errno_location;

int _sprintf(char* str, const char* fmt, va_list argptr) {
    int count = 0;
    const char* f = fmt;

    while(*f) {
        if(*f == '%' && *(f+1) == 's') {
            char* arg = va_arg(argptr, char*);
            while(*arg) {
                *str = *arg; arg++; str++;
            }
            f++;
            str--;
        } else {
            *str = *f;
        }
        f++;
        str++;
        count++;
    }
    *str = '\0';

    va_end(argptr);
    return count;
}

int sprintf(char* str, const char* fmt, ...) {
    int len;
    va_list argptr;
    va_start(argptr, fmt);
    len = _sprintf(str, fmt, argptr);
    va_end(argptr);
    return len;
}

int _fprintf(FILE* fp, const char* fmt, va_list argptr) {
    int len = strlen(fmt);
    char* msg = (char*)malloc(len+2);
    *msg = 1;
    strcpy((msg+1), fmt);
    GP2x_postMessage(GP2x_MESSAGE_FPRINTF, (unsigned long)GP2x_convert_ptr_to(msg), 0);
    va_end(argptr);
    return len;
}

int fprintf(FILE* fp, const char* fmt, ...){
    va_list argptr;
    va_start(argptr, fmt);
    return _fprintf(fp, fmt, argptr);
}

int puts(const char* s) {
    int len = strlen(s);
    char* msg = (char*)malloc(len+2);
    *msg = 1;
    strcpy((msg+1), s);
    GP2x_postMessage(GP2x_MESSAGE_FPRINTF, (unsigned long)GP2x_convert_ptr_to(msg), 0);
    return len;
}

int printf(const char* fmt, ...) {
    int len;
    va_list argptr;
    va_start(argptr, fmt);
    len = _fprintf(stdout, fmt, argptr);
    va_end(argptr);
    return len;
}

size_t strlen(const char* str) {
    int i = 0;
    while(*str) {
        i++;
        str++;
    }
    return i;
}

char* strcpy(char* dest, const char* src) {
    char* d = dest;
    while(*src) {
        *d = *src;
        d++;
        src++;
    }
    *d = '\0'; // Copy the null byte
    return dest;
}

char* strcat(char* dest, const char* src) {
    char* d = dest;
    while(*d) { d++; }
    while(*src) {
        *d = *src;
        d++;
        src++;
    }
    *d = '\0';
    return dest;
}

void exit(int code) {
    GP2x_postMessage(GP2x_MESSAGE_940_QUIT, (unsigned long)code, 1);
    while(1) {}
}
